interface objCompressed {
  width?: any;
  height?: any;
}
/**
 * 压缩图片
 * @param {file} file 文件file
 * @param {*} objCompressed objCompressed 可传图片宽高,高默认同比例
 * @returns
 */
export function compressImgs(
  file: any,
  objCompressed: objCompressed,
  type: string = "file"
) {
  console.log(objCompressed);
  return new Promise((resolve, reject) => {
    const windowURL = window.URL || window.webkitURL;
    const src = windowURL.createObjectURL(file);
    var img = new Image();
    img.src = src;

    img.onload = function (e: any) {
      var that: any = this;
      //默认压缩后图片规格
      var quality = 0.7;
      var wd = that.width;
      var hd = that.height;
      var scale = wd / hd;
      //实际要求
      const w = objCompressed.width || wd;
      const h = objCompressed.height || w / scale;
      //生成canvas
      var canvas = document.createElement("canvas");
      var ctx: any = canvas.getContext("2d");
      // 创建属性节点
      var anw = document.createAttribute("width");
      anw.nodeValue = w;
      var anh = document.createAttribute("height");
      anh.nodeValue = h;
      canvas.setAttributeNode(anw);
      canvas.setAttributeNode(anh);
      ctx.drawImage(that, 0, 0, w, h);
      var base64 = canvas.toDataURL("image/jpeg", quality);
      console.log(base64);

      const url = dataURLtoFile(base64, file.name, type);
      // 回调函数返回base64的值
      resolve(url);
    };
  });
}
/**
 * 把base64转file或者 url
 * file用于web， url 用于小程序类
 * @param dataurl base64
 * @param filename 名字
 * @returns
 */
export function dataURLtoFile(
  dataurl: any,
  filename: any = Date.now() + "",
  type: string = "file"
) {
  let arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  if (type == "file") {
    return new File([u8arr], filename, {
      type: mime,
    });
  } else {
    var url = URL || webkitURL;
    return url.createObjectURL(new Blob([u8arr], { type: mime }));
  }
}

/**
 * 公共的下载文件，根据传入的bolb 类型自动下载
 * @param data File | Blob
 * @param name  名字
 */
export const downloadFile = (data: File | Blob, name: string = "文件") => {
  var aDom = document.createElement("a"); // 创建一个 a 标签
  console.log(Object.prototype.toString.call(data));
  if (Object.prototype.toString.call(data) == "[object File]") {
    aDom.download = data.name || "文件"; // 设置文件名
  } else {
    aDom.download = name;
  }
  let href = URL.createObjectURL(data); // 将file对象转成 UTF-16 字符串
  console.log(data);
  aDom.href = href; // 放入href
  document.body.appendChild(aDom); // 将a标签插入 body
  aDom.click(); // 触发 a 标签的点击
  document.body.removeChild(aDom); // 移除刚才插入的 a 标签
  URL.revokeObjectURL(href); // 释放刚才生成的 UTF-16 字符串
};
